package com.rede.didiok.user.restapi;

import javax.annotation.Resource;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.rede.didiok.common.annotion.AvoidRepeatableCommit.AvoidRepeatableCommit;
import com.rede.didiok.common.annotion.log.BussinessLog;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.enums.BehaviorEnum;
import com.rede.didiok.common.feign.AdminFeignClient;
import com.rede.didiok.common.utils.ResultUtil;
import com.rede.didiok.common.utils.StringUtils;
import com.rede.didiok.user.service.UserService;

@RestController
@RequestMapping("/search/user")
@Api(value = "SQL搜索相关接口", tags = {"SQL搜索相关接口"})
@Slf4j
public class UserSearchRestApi {
    @Resource
    private UserService userService;
    @Resource
    private AdminFeignClient adminFeignClient;

    /**
     * 通过用户名查询相关用户信息
     *
     * @param keywords
     * @param currentPage
     * @param pageSize
     * @return
     */
    @AvoidRepeatableCommit(timeout = 500)
    @BussinessLog(value = "通过用户名搜索用户", behavior = BehaviorEnum.RANK_MEMBER_SEARCH)
    @ApiOperation(value = "通过用户名搜索用户", notes = "通过用户名搜索用户")
    @GetMapping("/searchByUser")
    public String searchByUser(@ApiParam(name = "keywords", value = "关键字", required = true) @RequestParam(required = true) String keywords,
                               @ApiParam(name = "currentPage", value = "当前页数", required = false) @RequestParam(name = "currentPage", required = false, defaultValue = "1") Long currentPage,
                               @ApiParam(name = "pageSize", value = "每页显示数目", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize) {
        if (StringUtils.isEmpty(keywords) || StringUtils.isEmpty(keywords.trim())) {
            return ResultUtil.resultWithMessage(SysConf.ERROR, MessageConf.KEYWORD_IS_NOT_EMPTY);
        }
        if (keywords.trim().length() <= 1 || keywords.trim().length() > 20) {
            return ResultUtil.resultWithMessage(SysConf.ERROR, "搜索长度必须在2~20个字符");
        }
        if (!StringUtils.checkNormalStr(keywords)) {
            return ResultUtil.resultWithMessage(SysConf.ERROR, "搜索内容包含特殊字符");
        }
        String searchSize = adminFeignClient.getSysParamsValueByKey(SysConf.SYS_SEARCH_SIZE);
        return ResultUtil.result(SysConf.SUCCESS, userService.getByUser(keywords, currentPage, Long.valueOf(searchSize)));

    }

}
